package com.poetize.plus.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.poetize.plus.utils.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 *
 * security退出登录处理器
 *
 * @author zuosy
 * @created 2024/3/28 15:56
 */
@Component
@RequiredArgsConstructor
public class LogOutHandler implements LogoutSuccessHandler {

    private final RedisTemplate<String, Object> redisTemplate;

    private final ObjectMapper objectMapper;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //请求头中获取token
        String header = request.getHeader("Authorization");
        if (StringUtils.hasText(header)){
            String token = header.replace("Bearer ", "");
            //删除token
            redisTemplate.delete(token);
            //删除refresh_token
            redisTemplate.delete("refresh_token:" + token);
            //返回信息
            response.setContentType("application/json;charset=UTF-8");
            ServletOutputStream out = response.getOutputStream();
            R<Boolean> ok = R.ok(true);
            out.write(objectMapper.writeValueAsString(ok).getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        }
    }
}
